<?php

abstract class Skjb_Db_Table_Row_Abstract extends Zend_Db_Table_Row_Abstract
{
    protected $_relations = array();
    
    public function __get($name)
    {
        if (in_array($name, $this->_relations)) {
            $functionName = 'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
            return $this->$functionName();
        }
        
        if (substr($name, -5) == 'Table') {
            return Skjb_Db_Table_Registry::getTable($name);
        }
        
        return parent::__get($name);
    }

   public function hasChanged($fields)
   {
       if (!is_array($fields)) {
           $field = $fields;
           $fields = array($field);
       }
       
       foreach ($fields as $field) {
           if (!isset($this->_cleanData[$field]) || $this->_cleanData[$field] != $this->_data[$field]) {
               return true;
           }
       }
       
       return false;
   }
    
    public function setFromArray(array $values, $limitFields = array(), $convertFields = array())
    {
        $setData = array();
        
        foreach ($values as $fieldName => $fieldValue) {
            if (is_array($convertFields) && count($convertFields) > 0 && isset($convertFields[$fieldName])) {
                $fieldName = $convertFields[$fieldName];
            }
            
            if (is_array($limitFields) && count($limitFields) > 0 && !in_array($fieldName, $limitFields)) {
                continue;
            }
            
            $setData[$fieldName] = $fieldValue;
        }
        
        parent::setFromArray($setData);

        return $this;
    }
    
    public function isValid($modifiedOnly = false)
    {
        if (is_array($modifiedOnly)) {
            $fields = $modifiedOnly;
        } else {
            $fields = ($modifiedOnly ? array_keys($this->_data) : array_keys($this->_modifiedFields));
        }
        
        $isValid = true;
        $messages = array();
        foreach ($fields as $name) {
            $this->_validateField($name, $isValid, $messages);
        }
        
        return ($isValid ? true : $messages);
    }
}